// 容器组件（container component）

import React, { Component } from 'react'
import { bindActionCreators } from 'redux'

import { connect } from 'react-redux'
import ProductsUi from './ProductsUi'

import * as ProductsActions from './actionCreator'
import { actionCreator as CartsActions } from '../carts'

@connect(
  state => ({
    products: state.product.all
  }),

  dispatch => {
    return {
      ...bindActionCreators(ProductsActions, dispatch),
      ...bindActionCreators(CartsActions, dispatch)
    }
  }
)
class Products extends Component {

  addProductToCart = product => {
    let { addProduct, decrementInventory, totalPrice } = this.props
    return (e) => {
      addProduct(product)
      decrementInventory(product)
      totalPrice()
    }
  }

  async componentDidMount() {
    this.props.loadDataAsync()
  }

  render() {
    let { products } = this.props
    return (
      <ProductsUi 
        products={products}
        addProductToCart={this.addProductToCart}
      ></ProductsUi>
    )
  }
}

export default Products;